package com.dpm.booksqr;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;


public class BookSqrActivity extends AbstractAsyncActivity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final Button loginButton = (Button) findViewById(R.id.btnLogin);
		loginButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new VerificarUsuario().execute(MediaType.APPLICATION_XML);
			}
		}

		);
	}

	private void mostrarUsuario(Usuario usuario) {
		// display a notification to the user with the state
		if (usuario != null) {
			//Toast.makeText(this, "Bienvenido a Booksquare " + usuario.getNombre() + "!", Toast.LENGTH_LONG).show();
			Intent i = new Intent(this, profile.class);
			Bundle b = new Bundle();
			b.putString("USUARIO_LOGIN", usuario.getUsuario());
			b.putString("USUARIO_PWD", usuario.getPassword());
			b.putString("USUARIO_NOMBRE", usuario.getNombre());
			b.putInt("USUARIO_PUNTAJE", usuario.getPuntaje());
			i.putExtras(b);
			
			startActivity(i);
		} else {
			Toast.makeText(this, "No se pudo ingresar con el usuario indicado. Por favor verifique",
					Toast.LENGTH_LONG).show();
		}
	}

	private class VerificarUsuario extends AsyncTask<MediaType, Void, Usuario> {

		private String sUsuario;
		private String sPassword;

		@Override
		protected void onPreExecute() {
			showLoadingProgressDialog("Verificando sus credenciales..");

			EditText txtUsuario = (EditText) findViewById(R.id.txtUsuario);
			sUsuario = txtUsuario.getText().toString();

			EditText txtPassword = (EditText) findViewById(R.id.txtPassword);
			sPassword = txtPassword.getText().toString();

		};

		@Override
		protected Usuario doInBackground(MediaType... params) {
			// TODO Auto-generated method stub
			try {
				if (params.length <= 0) {
					return null;
				}

				MediaType mediaType = params[0];
				final String url = getString(R.string.base_uri)
						+ "/usuarios/{username}/{pwd}";

				HttpHeaders requestHeaders = new HttpHeaders();
				List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
				acceptableMediaTypes.add(mediaType);
				requestHeaders.setAccept(acceptableMediaTypes);

				// Populate the headers in an HttpEntity object to use for the
				// request
				HttpEntity<?> requestEntity = new HttpEntity<Object>(
						requestHeaders);

				// Create a new RestTemplate instance
				RestTemplate restTemplate = new RestTemplate();

				// Perform the HTTP GET request
				ResponseEntity<Usuario> responseEntity = restTemplate.exchange(
						url, HttpMethod.GET, requestEntity, Usuario.class,
						sUsuario, sPassword);

				// Return the state from the ResponseEntity
				return responseEntity.getBody();
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Usuario usuario) {
			// hide the progress indicator when the network request is complete
			dismissProgressDialog();

			// return the list of states
			mostrarUsuario(usuario);
		}

	}
}